package com.jmgd.cjlx.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.jmgd.cjlx.constants.JztApplicationCommon;
import com.jmgd.cjlx.dao.*;
import com.jmgd.cjlx.entity.*;
import com.jmgd.cjlx.param.dz.*;
import com.jmgd.cjlx.param.jzt.DrugAdd;
import com.jmgd.cjlx.param.jzt.KcPriceResponse;
import com.jmgd.cjlx.param.jzt.KcPriceResult;
import com.jmgd.cjlx.param.jzt.TaXxYtq1Result;
import com.jmgd.cjlx.service.JztService;
import com.jmgd.cjlx.util.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;

@Service
public class JztServiceImpl implements JztService {
    private static final Logger logger = LoggerFactory.getLogger(JztServiceImpl.class);


    @Autowired
    TJztDrugMapper tJztDrugMapper;

    @Autowired
    TJztDrugTempMapper tJztDrugTempMapper;

    @Autowired
    TCjLxWarePriceMapper tCjLxWarePriceMapper;

    @Autowired
    TCjLxWareQtyMapper tCjLxWareQtyMapper;

    @Autowired
    TCjLxOrderHMapper tCjLxOrderHMapper;

    @Autowired
    TCjLxOrderDMapper tCjLxOrderDMapper;

    @Autowired
    TLxCallbackLogMapper tLxCallbackLogMapper;

    @Autowired
    TJztChTempMapper tJztChTempMapper;

    @Autowired
    TCjLxOrderTakeHMapper tCjLxOrderTakeHMapper;

    @Autowired
    TCjLxOrderTakeDMapper tCjLxOrderTakeDMapper;

    @Autowired
    TCjLxOrderSendHMapper tCjLxOrderSendHMapper;

    @Autowired
    TCjLxOrderSendDMapper tCjLxOrderSendDMapper;


    @Override
    public void addDrug() throws Exception{
        //填充数据
       tJztDrugMapper.addDrug();

        List<TJztDrugTemp> tJztDrugTempList = tJztDrugTempMapper.selectList(null);
        List<DrugAdd> list = new ArrayList<>();
        for(TJztDrugTemp tJztDrugTemp:tJztDrugTempList){
            DrugAdd obj1 = new DrugAdd();
            obj1.setZXSPBM(tJztDrugTemp.getZxspbm());
            obj1.setTYM(tJztDrugTemp.getTym());
            obj1.setYPJX(tJztDrugTemp.getYpjx());
            obj1.setGG(tJztDrugTemp.getGg());
            obj1.setBZSL(tJztDrugTemp.getBzsl());
            obj1.setBZDW(tJztDrugTemp.getBzdw());
            obj1.setZBZ(tJztDrugTemp.getZbz());
            obj1.setDBZ(tJztDrugTemp.getDbz());
            obj1.setYPPZWH(tJztDrugTemp.getYppzwh());
            obj1.setSCQYMC(tJztDrugTemp.getScqymc());
            obj1.setBRANCHID(tJztDrugTemp.getBranchid());
            obj1.setPLATID(tJztDrugTemp.getPlatid());
            obj1.setPLATNAME(tJztDrugTemp.getPlatname());
            obj1.setADDTIME(new Date());
            list.add(obj1);
        }

        if(list.size()> 0) {
            ObjectMapper mapper = new ObjectMapper();
            String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(list);
            logger.info(jsonString);

            Map<String, String> params = new HashMap<>();
            params.put("Authorization", "Bearer " +getToken());

            String result = HttpClientUtil.doPost2(JztApplicationCommon.BASEURL + JztApplicationCommon.ADDDRUGBASE, params, jsonString);
            logger.info(result);
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(result);
            //{"code":200,"success":true,"msg":"操作成功","data":true}
            if(rootNode.get("data").asBoolean()){
                tJztDrugMapper.addDrugFinish();
            }
        }
    }

    @Override
    public String getToken() throws JsonProcessingException {
        String urlString = JztApplicationCommon.BASEURL+ JztApplicationCommon.GETTOKEN;
        String urlParameters = "grant_type=client_credentials&client_id="+JztApplicationCommon.CLIENTID+"&client_secret="+JztApplicationCommon.CLIENTSECRET;

        String jsonResponse = HttpClientUtil.doPost1(urlString,urlParameters);

        ObjectMapper objectMapper = new ObjectMapper();

        // 解析外层的 JSON 对象
        JsonNode rootNode = objectMapper.readTree(jsonResponse);
        String accessToken = rootNode.get("access_token").asText();
        return accessToken;
    }

    @Override
    public void getWareKcAndPrice() throws JsonProcessingException {
        Map<String, String> paramHeaders = new HashMap<>();
        paramHeaders.put("Authorization", "Bearer " +getToken());

        Map<String, String> params= new HashMap<>();
        params.put("branchId",JztApplicationCommon.BRANCHID);
        params.put("platId",JztApplicationCommon.PLATID);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime now = LocalDateTime.now();
        // 当前日期减去10天
        LocalDateTime tenDaysAgo = now.minus(365, ChronoUnit.DAYS);
        String formattedDate = tenDaysAgo.format(formatter);
        params.put("lastModifyTime",formattedDate);

        params.put("pageIndex","1");
        params.put("pageSize","200");

        String urlString = JztApplicationCommon.BASEURL+ JztApplicationCommon.GETSTORAGE1;

        String jsonResponse = HttpClientUtil.doGet1(urlString,paramHeaders,params);

        ObjectMapper mapper = new ObjectMapper();
        KcPriceResponse response = mapper.readValue(jsonResponse, KcPriceResponse.class);

        if(response.isSuccess()){
            List<KcPriceResult> kcPriceResultList= response.getData().getResult();

            int j = (int) Math.ceil(response.getData().getRecordCount()/200);//计算还要多少次循环
            for(int i = 2;i<=j;i++){
                params.put("pageIndex",String.valueOf(i));
                jsonResponse = HttpClientUtil.doGet1(urlString,paramHeaders,params);
                response = mapper.readValue(jsonResponse, KcPriceResponse.class);
                kcPriceResultList.addAll(response.getData().getResult());
            }


            QueryWrapper<TCjLxWarePrice> queryWrapperPrice = new QueryWrapper<>();
            queryWrapperPrice.eq("compname","九州通");
            tCjLxWarePriceMapper.delete(queryWrapperPrice);

            QueryWrapper<TCjLxWareQty> queryWrapperQty = new QueryWrapper<>();
            queryWrapperQty.eq("compname","九州通");
            tCjLxWareQtyMapper.delete(queryWrapperQty);

            for(KcPriceResult kcPriceResult:kcPriceResultList){
                TCjLxWarePrice tCjLxWarePrice = new TCjLxWarePrice();
                tCjLxWarePrice.setGoodsid(kcPriceResult.getSpBh());
                tCjLxWarePrice.setCompname("九州通");
                tCjLxWarePrice.setCreatedatetime(new Date());
                tCjLxWarePrice.setPrice(kcPriceResult.getHuiyTj());
                tCjLxWarePrice.setWareid(Long.valueOf(kcPriceResult.getSpBh_Kh()));

                tCjLxWarePriceMapper.insert(tCjLxWarePrice);

                TCjLxWareQty tCjLxWareQty = new TCjLxWareQty();
                tCjLxWareQty.setGoodsid(kcPriceResult.getSpBh());
                tCjLxWareQty.setCompname("九州通");
                tCjLxWareQty.setCreatedatetime(new Date());
                tCjLxWareQty.setQty(kcPriceResult.getShl().toString());
                tCjLxWareQty.setWareid(Long.valueOf(kcPriceResult.getSpBh_Kh()));

                tCjLxWareQtyMapper.insert(tCjLxWareQty);
            }
        }
//        ObjectMapper objectMapper = new ObjectMapper();
//
//        // 解析外层的 JSON 对象
//        JsonNode rootNode = objectMapper.readTree(jsonResponse);
//
//        if(rootNode.get("success").asBoolean()){
//            JsonNode rootNodeData = rootNode.get("data");
//            int recordCount = rootNodeData.get("RecordCount").asInt();
//            //rootNodeData.get("RecordCount").asInt()
//        }

    }



    @Override
    public void insertCgxx(String compname,String ordercode) throws JsonProcessingException {

        QueryWrapper<TCjLxOrderH> queryWrapperH = new QueryWrapper<>();
        queryWrapperH.eq("compname", compname).eq("ordercode", ordercode);
        List<TCjLxOrderH> tCjLxOrderHList = tCjLxOrderHMapper.selectList(queryWrapperH);
        if (tCjLxOrderHList.size() > 0) {
            TCjLxOrderH tCjLxOrderH = tCjLxOrderHList.get(0);
            // 创建一个 OffsetDateTime 实例
            OffsetDateTime now = OffsetDateTime.now(ZoneOffset.of("+08:00"));

            // 定义日期时间格式
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSXXX");

            // 格式化日期时间
            String formattedDateTime = now.format(formatter);

            // 输出格式化的日期时间
            System.out.println(formattedDateTime);


            ObjectMapper mapper = new ObjectMapper();
            ArrayNode rootArray = mapper.createArrayNode();

            // 创建主节点
            ObjectNode mainNode = mapper.createObjectNode();
            mainNode.put("BranchId", JztApplicationCommon.BRANCHID);
            mainNode.put("PlatId", JztApplicationCommon.PLATID);
            mainNode.put("Rq", formattedDateTime);
            mainNode.put("DjBh", tCjLxOrderH.getOrdercode());

            mainNode.put("DwBh", JztApplicationCommon.DWBH);

            mainNode.put("ISPAY", 0);

            // 创建 OrderDetail 数组
            ArrayNode orderDetailArray = mapper.createArrayNode();


            QueryWrapper<TCjLxOrderD> queryWrapperD = new QueryWrapper<>();
            queryWrapperD.eq("compname", compname).eq("ordercode", ordercode);
            List<TCjLxOrderD> tCjLxOrderDList = tCjLxOrderDMapper.selectList(queryWrapperD);

            List<Map<String, Object>> orderDetails = new ArrayList<>();

            BigDecimal number1 = new BigDecimal("0");
            for (TCjLxOrderD tCjLxOrderD : tCjLxOrderDList) {
                Map<String, Object> orderDetail1 = new HashMap<>();
                orderDetail1.put("DjMxBh", tCjLxOrderD.getOrdercode()+tCjLxOrderD.getItemcode().toString());
                orderDetail1.put("SpBh", tCjLxOrderD.getWarecode());
                orderDetail1.put("SpMc", tCjLxOrderD.getCjwarename());
                number1 = number1.add(tCjLxOrderD.getOrderprice().multiply(new BigDecimal(tCjLxOrderD.getGoodsorderqty())));
                orderDetail1.put("HsJe", tCjLxOrderD.getOrderprice().multiply(new BigDecimal(tCjLxOrderD.getGoodsorderqty())));
                orderDetail1.put("Shl", tCjLxOrderD.getGoodsorderqty());
                orderDetail1.put("dj", tCjLxOrderD.getOrderprice());
                orderDetail1.put("ProType", null);
                orderDetail1.put("PrintPrice", "");
                orderDetail1.put("Xh", tCjLxOrderD.getItemcode());
                orderDetail1.put("Bz", null);

                orderDetails.add(orderDetail1);
            }
            mainNode.put("RowNum", tCjLxOrderDList.size());
            mainNode.put("HsJeHz", number1);


            // 填充数据源
            //List<Map<String, Object>> orderDetails = getOrderDetails();

            // 遍历数据源并创建 JSON 节点
            for (Map<String, Object> detail : orderDetails) {
                ObjectNode orderDetail = createNodeWithFields(mapper, detail);
                orderDetailArray.add(orderDetail);
            }

            // 将 OrderDetail 数组添加到主节点
            mainNode.set("OrderDetail", orderDetailArray);

            // 将主节点添加到根数组
            rootArray.add(mainNode);

            // 输出 JSON
            try {
                String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootArray);

                Map<String, String> paramHeaders = new HashMap<>();
                paramHeaders.put("Authorization", "Bearer " +getToken());


                String urlString = JztApplicationCommon.BASEURL+ JztApplicationCommon.INSERTCGXX;

                logger.info("九州通下订单参数："+jsonString);
                String jsonResult = HttpClientUtil.doPost2(urlString,paramHeaders,jsonString);

                logger.info("九州通下订单返回："+jsonResult);

                ObjectMapper mapperResult = new ObjectMapper();

                // 解析 JSON 字符串为 JsonNode 对象
                JsonNode rootNode = mapperResult.readTree(jsonResult);

                // 提取字段
                if(rootNode.get("code").asInt()==200){
                    tCjLxOrderH.setStatus1(0);
                    tCjLxOrderH.setErrormsg(rootNode.get("msg").asText());
                    tCjLxOrderH.setErrorcode(rootNode.get("code").asInt());
                }else{
                    tCjLxOrderH.setStatus1(-1);
                    tCjLxOrderH.setErrormsg(rootNode.get("msg").asText());
                    tCjLxOrderH.setErrorcode(rootNode.get("code").asInt());
                }
                QueryWrapper<TCjLxOrderH> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("compname",compname).eq("ordercode",tCjLxOrderH.getOrdercode());
                tCjLxOrderHMapper.update(tCjLxOrderH,queryWrapper);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


        // 创建节点并设置字段和值
        private ObjectNode createNodeWithFields(ObjectMapper mapper, Map<String, Object> fields) {
            ObjectNode node = mapper.createObjectNode();
            for (Map.Entry<String, Object> entry : fields.entrySet()) {
                if (entry.getValue() == null) {
                    node.putNull(entry.getKey());
                } else if (entry.getValue() instanceof String) {
                    node.put(entry.getKey(), (String) entry.getValue());
                } else if (entry.getValue() instanceof Integer) {
                    node.put(entry.getKey(), (Integer) entry.getValue());
                } else if (entry.getValue() instanceof Double) {
                    node.put(entry.getKey(), (Double) entry.getValue());
                }else if (entry.getValue() instanceof BigDecimal) {
                    node.put(entry.getKey(), (BigDecimal) entry.getValue());
                }
                // 可以根据需要添加更多类型
            }
            return node;
        }

    @Override
    public void getTaXxYtq1() throws JsonProcessingException {
        Map<String, String> paramHeaders = new HashMap<>();
        paramHeaders.put("Authorization", "Bearer " +getToken());

        Map<String, String> params= new HashMap<>();
        params.put("branchId",JztApplicationCommon.BRANCHID);
        params.put("platId",JztApplicationCommon.PLATID);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime now = LocalDateTime.now();
        // 当前日期减去10天
        LocalDateTime tenDaysAgo = now.minus(10, ChronoUnit.DAYS);
        String formattedDate = tenDaysAgo.format(formatter);
        params.put("startTime",formattedDate);

        params.put("djBs",JztApplicationCommon.XSA);

        params.put("pageIndex","1");
        params.put("pageSize","1000");

        params.put("isUploadDD","false");

        String urlString = JztApplicationCommon.BASEURL+ JztApplicationCommon.GETTAXXYTQ1;

        logger.info("九州通查询出库url"+urlString);

        String jsonResponse = HttpClientUtil.doGet1(urlString,paramHeaders,params);

        logger.info("九州通查询返回"+urlString);

        org.json.JSONObject jsonObject = new org.json.JSONObject(jsonResponse);
        boolean success = jsonObject.getBoolean("success");

        if(success) {
            String dataString = jsonObject.getString("data");

            // 解析内层 JSON 对象
            org.json.JSONObject dataObject = new org.json.JSONObject(dataString);
            org.json.JSONArray resultArray = dataObject.getJSONArray("Result");

            tJztChTempMapper.delete(null);

            for (int i = 0; i < resultArray.length(); i++) {
                org.json.JSONObject resultObject = resultArray.getJSONObject(i);

                TJztChTemp tJztChTemp = new TJztChTemp();

                tJztChTemp.setBaozhiqi(resultObject.getString("BaoZhiQi"));
                tJztChTemp.setBeizhu(resultObject.getString("BeiZhu"));
                tJztChTemp.setBranchid(resultObject.getString("BranchId"));
                tJztChTemp.setDdshl(resultObject.getDouble("DdShl"));
                tJztChTemp.setDj(resultObject.getDouble("Dj"));
                tJztChTemp.setDjbh(resultObject.getString("DjBh"));
                tJztChTemp.setDw(resultObject.getString("Dw"));
                tJztChTemp.setDwbh(resultObject.optString("DwBh", null));
                tJztChTemp.setDwmch(resultObject.getString("DwMch"));
                tJztChTemp.setHsje(resultObject.getDouble("HsJe"));
                tJztChTemp.setHsjehz(resultObject.getDouble("HsJeHz"));
                tJztChTemp.setJgm(resultObject.optString("Jgm", null));
                tJztChTemp.setJqcbj(resultObject.getDouble("JqCbj"));
                tJztChTemp.setJztshlv(resultObject.getString("JztShLv"));
                tJztChTemp.setKaipiaodjbh(resultObject.getString("KaiPiaoDjBh"));
                tJztChTemp.setMxdjbh(resultObject.optString("MxDjBh", null));
                tJztChTemp.setPihao(resultObject.getString("PiHao"));
                tJztChTemp.setRq(resultObject.getString("Rq"));
                tJztChTemp.setSl(resultObject.getDouble("Shl"));
                tJztChTemp.setShpchd(resultObject.getString("ShpChd"));
                tJztChTemp.setSonghdz(resultObject.getString("SonghDz"));
                tJztChTemp.setSonghtime(resultObject.optString("SonghTime", null));
                tJztChTemp.setSpbh(resultObject.getString("SpBh"));
                tJztChTemp.setSpmch(resultObject.getString("SpMch"));
                tJztChTemp.setSxrq(resultObject.getString("SxRq"));
                tJztChTemp.setXgdjbh(resultObject.optString("XgDjBh", null));
                tJztChTemp.setZt(resultObject.getInt("Zt"));
                tJztChTemp.setCkmxpk(resultObject.getLong("CkMxPk"));
                tJztChTemp.setPzwh(resultObject.optString("pzwh", null));

                tJztChTempMapper.insert(tJztChTemp);

            }
            tJztChTempMapper.insertTjztch();
        }

    }

    @Override
    public void callBack(Object object) {
        String compname = "九州通";
        TLxCallbackLog tLxCallbackLog = new TLxCallbackLog();
        String jsonString = JSONObject.toJSONString(object);
        logger.info("回调："+jsonString);
        tLxCallbackLog.setJsondata(jsonString);
        tLxCallbackLog.setCreatedate(new Date());
        tLxCallbackLog.setCompname(compname);
        tLxCallbackLogMapper.insert(tLxCallbackLog);

//        String jsonString = "{\"method\": \"m_shipments_callback\", \"content\": \"{\\\"ordercode\\\":\\\"2407310001\\\",\\\"b2bordercode\\\":\\\"11111111\\\",\\\"shipments\\\":[{\\\"itemcode\\\":\\\"1\\\",\\\"dispenseno\\\":\\\"95236525\\\",\\\"goodsid\\\":\\\"C078703N\\\",\\\"shipmentsQty\\\":1000,\\\"batch\\\":\\\"2404502A\\\",\\\"validity\\\":\\\"2026-03-31\\\",\\\"proddate\\\":\\\"2024-04-22\\\",\\\"shipmentsPrice\\\":27.00000000,\\\"shipmentsTotalPrice\\\":27000.00000000,\\\"shipmentsDate\\\":\\\"2024-08-06 21:03:05\\\",\\\"targetDate\\\":\\\"2024-08-06 19:00:14\\\",\\\"signforno\\\":\\\"25172735\\\"}]}\"}\n";

        BaseCallBackResponse baseCallBackResponse = JSONObject.parseObject(jsonString, BaseCallBackResponse.class);
        if(baseCallBackResponse.getMethod().equals("m_create_order_callback")){
            OrderCreateResponse orderCreateResponse= JSONObject.parseObject(baseCallBackResponse.getContent(),
                    new TypeReference<OrderCreateResponse>(){});

            QueryWrapper<TCjLxOrderH> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("ordercode",orderCreateResponse.getOrdercode());
            List<TCjLxOrderH> tCjLxOrderHList =  tCjLxOrderHMapper.selectList(queryWrapper);
            if(tCjLxOrderHList.size() == 1){
                TCjLxOrderH tCjLxOrderH = tCjLxOrderHList.get(0);
                compname =tCjLxOrderH.getCompname();
                tCjLxOrderH.setStatus1(orderCreateResponse.getStatus());
                tCjLxOrderH.setErrorcode(orderCreateResponse.getErrorcode());
                tCjLxOrderH.setTotal(orderCreateResponse.getTotal());
                tCjLxOrderH.setB2bordercode(orderCreateResponse.getB2bordercode());
                tCjLxOrderH.setErrormsg(orderCreateResponse.getErrormsg());
                tCjLxOrderH.setUpdatedatetime(new Date());
                tCjLxOrderHMapper.update(tCjLxOrderH,queryWrapper);

                for(OrderCreateResponseDetail orderCreateResponseDetail:orderCreateResponse.getItems()){
//                    QueryWrapper<TCjLxOrderD> queryWrapperD = new QueryWrapper<>();
//                    queryWrapperD.eq("compname",compname)
//                            .eq("ordercode",orderCreateResponse.getOrdercode())
//                            .eq("itemcode",orderCreateResponseDetail.getItemcode());
//                    List<TCjLxOrderD> tCjLxOrderDList =  tCjLxOrderDMapper.selectTCjLxOrderD(orderCreateResponseDetail.getItemcode(),orderCreateResponse.getOrdercode());
//                    if(tCjLxOrderDList.size() == 1){
//                        TCjLxOrderD tCjLxOrderD = tCjLxOrderDList.get(0);
//                        tCjLxOrderD.setB2bordercode(orderCreateResponse.getB2bordercode());
//                        tCjLxOrderD.setPrice(orderCreateResponseDetail.getPrice());
//                        tCjLxOrderD.setGoodsqty(orderCreateResponseDetail.getGoodsqty());
//                        tCjLxOrderD.setSubtotal(orderCreateResponseDetail.getSubtotal());
//                        tCjLxOrderD.setUpdatedatetime(new Date());

                        tCjLxOrderDMapper.updateTCjLxOrderD(orderCreateResponseDetail.getItemcode(),orderCreateResponse.getOrdercode(),
                                orderCreateResponse.getB2bordercode(),orderCreateResponseDetail.getPrice(),orderCreateResponseDetail.getGoodsqty(),
                                orderCreateResponseDetail.getSubtotal());
//                    }

                }
            }
        }else if(baseCallBackResponse.getMethod().equals("m_dispense_callback")){//配货

            OrderTakeResponse orderTakeResponse= JSONObject.parseObject(baseCallBackResponse.getContent(),
                    new TypeReference<OrderTakeResponse>(){});


            QueryWrapper<TCjLxOrderH> queryWrapperOrderH = new QueryWrapper<>();
            queryWrapperOrderH.eq("ordercode",orderTakeResponse.getOrdercode());
            List<TCjLxOrderH> tCjLxOrderHList =  tCjLxOrderHMapper.selectList(queryWrapperOrderH);

            if(tCjLxOrderHList.size() == 1){
                TCjLxOrderH tCjLxOrderH = tCjLxOrderHList.get(0);
                compname = tCjLxOrderH.getCompname();
            }


            QueryWrapper<TCjLxOrderTakeH> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("compname",compname).eq("ordercode",orderTakeResponse.getOrdercode());
            List<TCjLxOrderTakeH> tCjLxOrderTakeHList =  tCjLxOrderTakeHMapper.selectList(queryWrapper);
            if(tCjLxOrderTakeHList.size() > 0){

            }else{
                TCjLxOrderTakeH tCjLxOrderTakeH = new TCjLxOrderTakeH();
                tCjLxOrderTakeH.setB2bordercode(orderTakeResponse.getB2bordercode());
                tCjLxOrderTakeH.setCompname(compname);
                tCjLxOrderTakeH.setCreatedatetime(new Date());
                tCjLxOrderTakeH.setOrdercode(orderTakeResponse.getOrdercode());
                tCjLxOrderTakeHMapper.insert(tCjLxOrderTakeH);
            }


            for(OrderTakeResponseDetail orderTakeResponseDetail:orderTakeResponse.getDispense()){
                TCjLxOrderTakeD tCjLxOrderTakeD = new TCjLxOrderTakeD();
                tCjLxOrderTakeD.setB2bordercode(orderTakeResponse.getB2bordercode());
                tCjLxOrderTakeD.setOrdercode(orderTakeResponse.getOrdercode());
                tCjLxOrderTakeD.setCompname(compname);
                tCjLxOrderTakeD.setCreatedatetime(new Date());
                tCjLxOrderTakeD.setItemcode(orderTakeResponseDetail.getItemcode());
                tCjLxOrderTakeD.setDispenseno(orderTakeResponseDetail.getDispenseno());
                tCjLxOrderTakeD.setGoodsid(orderTakeResponseDetail.getGoodsid());
                tCjLxOrderTakeD.setDispenseno(orderTakeResponseDetail.getDispenseno());
                tCjLxOrderTakeD.setStatus(orderTakeResponseDetail.getStatus());
                tCjLxOrderTakeD.setGoodsqty(orderTakeResponseDetail.getGoodsqty());
                tCjLxOrderTakeD.setBatchdata(orderTakeResponseDetail.getBatch());
                tCjLxOrderTakeD.setValidity(orderTakeResponseDetail.getValidity());
                tCjLxOrderTakeD.setProddate(orderTakeResponseDetail.getProddate());
                tCjLxOrderTakeDMapper.insert(tCjLxOrderTakeD);
            }
        }else if(baseCallBackResponse.getMethod().equals("m_shipments_callback")){//发货
            OrderSendResponse orderSendResponse= JSONObject.parseObject(baseCallBackResponse.getContent(),
                    new TypeReference<OrderSendResponse>(){});

            QueryWrapper<TCjLxOrderH> queryWrapperOrderH = new QueryWrapper<>();
            queryWrapperOrderH.eq("ordercode",orderSendResponse.getOrdercode());
            List<TCjLxOrderH> tCjLxOrderHList =  tCjLxOrderHMapper.selectList(queryWrapperOrderH);

            if(tCjLxOrderHList.size() == 1){
                TCjLxOrderH tCjLxOrderH = tCjLxOrderHList.get(0);
                compname = tCjLxOrderH.getCompname();
            }

            QueryWrapper<TCjLxOrderSendH> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("compname",compname).eq("ordercode",orderSendResponse.getOrdercode());
            List<TCjLxOrderSendH> tCjLxOrderSendHList = tCjLxOrderSendHMapper.selectList(queryWrapper);
            if(tCjLxOrderSendHList.size() > 0){

            }else{
                TCjLxOrderSendH tCjLxOrderSendH = new TCjLxOrderSendH();
                tCjLxOrderSendH.setB2bordercode(orderSendResponse.getB2bordercode());
                tCjLxOrderSendH.setCompname(compname);
                tCjLxOrderSendH.setCreatedatetime(new Date());
                tCjLxOrderSendH.setOrdercode(orderSendResponse.getOrdercode());
                tCjLxOrderSendHMapper.insert(tCjLxOrderSendH);
            }


            for(OrderSendResponseDetail orderSendResponseDetail:orderSendResponse.getShipments()){
                TCjLxOrderSendD tCjLxOrderSendD = new TCjLxOrderSendD();
                tCjLxOrderSendD.setB2bordercode(orderSendResponse.getB2bordercode());
                tCjLxOrderSendD.setOrdercode(orderSendResponse.getOrdercode());
                tCjLxOrderSendD.setCompname(compname);
                tCjLxOrderSendD.setCreatedatetime(new Date());
                tCjLxOrderSendD.setItemcode(orderSendResponseDetail.getItemcode());
                tCjLxOrderSendD.setGoodsid(orderSendResponseDetail.getGoodsid());
                tCjLxOrderSendD.setDispenseno(orderSendResponseDetail.getDispenseno());
                tCjLxOrderSendD.setShipmentsqty(orderSendResponseDetail.getShipmentsQty());
                tCjLxOrderSendD.setBatchdata(orderSendResponseDetail.getBatch());
                tCjLxOrderSendD.setValidity(orderSendResponseDetail.getValidity());
                tCjLxOrderSendD.setProddate(orderSendResponseDetail.getProddate());
                tCjLxOrderSendD.setShipmentsprice(orderSendResponseDetail.getShipmentsPrice());
                tCjLxOrderSendD.setShipmentstotalprice(orderSendResponseDetail.getShipmentsTotalPrice());
                tCjLxOrderSendD.setShipmentsdate(orderSendResponseDetail.getShipmentsDate());
                tCjLxOrderSendD.setTargetdate(orderSendResponseDetail.getTargetDate());
                tCjLxOrderSendD.setSignforno(orderSendResponseDetail.getSignforno());

                tCjLxOrderSendDMapper.insert(tCjLxOrderSendD);
            }
        }
    }


    public static void main(String[] args) {
        String jsonString = "{ \"success\":true, \"code\":\"200\", \"msg\":\"请求响应成功!\", \"data\":\"{\\\"Result\\\": [{\\\"BaoZhiQi\\\":\\\"2024/5/12 0:00:00\\\",\\\"BeiZhu\\\":\\\"Z000472306004\\\",\\\"BranchId\\\":\\\"FDS\\\",\\\"DdShl\\\":44.0,\\\"Dj\\\":52.0,\\\"DjBh\\\":\\\"FDSXHR09102562\\\",\\\"Dw\\\":\\\"盒\\\",\\\"DwBh\\\":null,\\\"DwMch\\\":\\\"国控国大(江门)医药有限公司\\\",\\\"HsJe\\\":2288.0,\\\"HsJeHz\\\":4650.0,\\\"Jgm\\\":null,\\\"JqCbj\\\":47.20,\\\"JztShLv\\\":\\\"0.13\\\",\\\"KaiPiaoDjBh\\\":\\\"FDSXSG09420113\\\",\\\"MxDjBh\\\":null,\\\"PiHao\\\":\\\"A240502\\\",\\\"Rq\\\":\\\"2024/8/6 0:00:00\\\",\\\"Shl\\\":44.0,\\\"ShpChd\\\":\\\"湖北金贵中药饮片有限公司\\\",\\\"SonghDz\\\":\\\"江门市蓬江区建设三路173号16幢首层第1间、第2间、第3间、二楼\\\",\\\"SonghTime\\\":null,\\\"SpBh\\\":\\\"Z000472306004\\\",\\\"SpMch\\\":\\\"熊胆粉\\\",\\\"SxRq\\\":\\\"2027/5/11 0:00:00\\\",\\\"XgDjBh\\\":null,\\\"Zt\\\":0,\\\"CkMxPk\\\":558084000031,\\\"pzwh\\\":null}, {\\\"BaoZhiQi\\\":\\\"2024/5/11 0:00:00\\\",\\\"BeiZhu\\\":\\\"Z000472306004\\\",\\\"BranchId\\\":\\\"FDS\\\",\\\"DdShl\\\":6.0,\\\"Dj\\\":52.0,\\\"DjBh\\\":\\\"FDSXHR09102562\\\",\\\"Dw\\\":\\\"盒\\\",\\\"DwBh\\\":null,\\\"DwMch\\\":\\\"国控国大(江门)医药有限公司\\\",\\\"HsJe\\\":312.0,\\\"HsJeHz\\\":4650.0,\\\"Jgm\\\":null,\\\"JqCbj\\\":47.20,\\\"JztShLv\\\":\\\"0.13\\\",\\\"KaiPiaoDjBh\\\":\\\"FDSXSG09420113\\\",\\\"MxDjBh\\\":null,\\\"PiHao\\\":\\\"A240501\\\",\\\"Rq\\\":\\\"2024/8/6 0:00:00\\\",\\\"Shl\\\":6.0,\\\"ShpChd\\\":\\\"湖北金贵中药饮片有限公司\\\",\\\"SonghDz\\\":\\\"江门市蓬江区建设三路173号16幢首层第1间、第2间、第3间、二楼\\\",\\\"SonghTime\\\":null,\\\"SpBh\\\":\\\"Z000472306004\\\",\\\"SpMch\\\":\\\"熊胆粉\\\",\\\"SxRq\\\":\\\"2027/5/10 0:00:00\\\",\\\"XgDjBh\\\":null,\\\"Zt\\\":0,\\\"CkMxPk\\\":558084010031,\\\"pzwh\\\":null}] ,\\\"RecordCount\\\":96}\" }";

        // 解析外层 JSON 对象
        org.json.JSONObject jsonObject = new org.json.JSONObject(jsonString);
        boolean success = jsonObject.getBoolean("success");
        String code = jsonObject.getString("code");
        String msg = jsonObject.getString("msg");
        String dataString = jsonObject.getString("data");

        // 解析内层 JSON 对象
        org.json.JSONObject dataObject = new org.json.JSONObject(dataString);
        org.json.JSONArray resultArray = dataObject.getJSONArray("Result");

        for (int i = 0; i < resultArray.length(); i++) {
            org.json.JSONObject resultObject = resultArray.getJSONObject(i);
            TaXxYtq1Result result = new TaXxYtq1Result();

            result.setBaoZhiQi(resultObject.getString("BaoZhiQi"));
            result.setBeiZhu(resultObject.getString("BeiZhu"));
            result.setBranchId(resultObject.getString("BranchId"));
            result.setDdShl(resultObject.getDouble("DdShl"));
            result.setDj(resultObject.getDouble("Dj"));
            result.setDjBh(resultObject.getString("DjBh"));
            result.setDw(resultObject.getString("Dw"));
            result.setDwBh(resultObject.optString("DwBh", null));
            result.setDwMch(resultObject.getString("DwMch"));
            result.setHsJe(resultObject.getDouble("HsJe"));
            result.setHsJeHz(resultObject.getDouble("HsJeHz"));
            result.setJgm(resultObject.optString("Jgm", null));
            result.setJqCbj(resultObject.getDouble("JqCbj"));
            result.setJztShLv(resultObject.getString("JztShLv"));
            result.setKaiPiaoDjBh(resultObject.getString("KaiPiaoDjBh"));
            result.setMxDjBh(resultObject.optString("MxDjBh", null));
            result.setPiHao(resultObject.getString("PiHao"));
            result.setRq(resultObject.getString("Rq"));
            result.setShl(resultObject.getDouble("Shl"));
            result.setShpChd(resultObject.getString("ShpChd"));
            result.setSonghDz(resultObject.getString("SonghDz"));
            result.setSonghTime(resultObject.optString("SonghTime", null));
            result.setSpBh(resultObject.getString("SpBh"));
            result.setSpMch(resultObject.getString("SpMch"));
            result.setSxRq(resultObject.getString("SxRq"));
            result.setXgDjBh(resultObject.optString("XgDjBh", null));
            result.setZt(resultObject.getInt("Zt"));
            result.setCkMxPk(resultObject.getLong("CkMxPk"));
            result.setPzwh(resultObject.optString("pzwh", null));

            // 输出结果对象内容
            System.out.println(result);
        }

//        ObjectMapper mapper = new ObjectMapper();
//        ArrayNode rootArray = mapper.createArrayNode();
//
//        // 创建主节点
//        ObjectNode mainNode = mapper.createObjectNode();
//        mainNode.put("BranchId", "FDS");
//        mainNode.put("PlatId", "PTZS001");
//        mainNode.put("Rq", "2024-07-30T09:15:49.516000+08:00");
//        mainNode.put("DjBh", "100001");
//        mainNode.put("HsJeHz", 10);
//        mainNode.put("DwBh", "B440703002X001GA");
//        mainNode.put("RowNum", 2);
//        mainNode.put("ISPAY", 0);
//
//        // 创建 OrderDetail 数组
//        ArrayNode orderDetailArray = mapper.createArrayNode();
//
//        // 填充数据源
//        List<Map<String, Object>> orderDetails = getOrderDetails();
//
//        // 遍历数据源并创建 JSON 节点
//        for (Map<String, Object> detail : orderDetails) {
//            ObjectNode orderDetail = createNodeWithFields(mapper, detail);
//            orderDetailArray.add(orderDetail);
//        }
//
//        // 将 OrderDetail 数组添加到主节点
//        mainNode.set("OrderDetail", orderDetailArray);
//
//        // 将主节点添加到根数组
//        rootArray.add(mainNode);
//
//        // 输出 JSON
//        try {
//            String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootArray);
//            System.out.println(jsonString);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        }


}
